(function (doc, win, undefined) {
    //统计配置
    var cfg = {
        id: "09c5d4daddb9b6250ba93075257e58a2",//site account id
        dm: ["10.34.7.164"],//account domain
        age: 31536000000,
        sindex: [1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
        sengin: ["baidu.com", "baidu.com", "google.com", "google.com.hk", "sogou.com", "zhongsou.com", "search.yahoo.com", "one.cn.yahoo.com", "soso.com", "114search.118114.cn", "search.live.com", "youdao.com", "gougou.com", "bing.com"],
        sword: ["word", "wd", "q", "q", "query", "w", "p", "p", "w", "kw", "q", "q", "search", "q"]
    };
    
    // addevent
    function addEvent(obj, type, fn) {
        obj.attachEvent ? obj.attachEvent("on" + type, function (type) {
            fn.call(obj, type)
        }) : obj.addEventListener && obj.addEventListener(type, fn, false)
    }
    var now = (new Date).getTime(),//time
        //ds 分辨率
        //cl 颜色质量
        //ck 是否启用cookie true or false
        //ja 是否启用java
        //ln 语言
        //si 帐号
        //su 来源
        //sw 关键词
        //se 搜索引擎编号
        //st 来源类型 2 搜索 1站外 0本站
        //rnd 随机数
		// fl flash 版本
        param = ["ck", "cl", "ds", "ja", "ln", "rnd", "se", "si", "st", "su", "sw","uid","sid","fl","dt","du"];//url param
    
    
    var mix = function(des, src, override) {
        var isArray = function(obj) {
            return Object.prototype.toString.call(obj) === "[object Array]" || (obj instanceof Array);
        };
        if (isArray(src)) {
            for (var i = 0, len = src.length; i < len; i++) {
                mix(des, src[i], override);
            }
            return des;
        }
        for (i in src) {
            if (override || !(des[i] || (i in des))) {
                des[i] = src[i];
            }
        }
        return des;
    };
    function main() {
        this.data = {};
        this.getData();
        this.log();
    }

    mix(main.prototype,{
        protocol: function () {
            return doc.location.protocol == "https:" ? "https://" : "http://"
        },
        //随机数
        getRnd: function () {
            this.a.rnd = Math.round(Math.random() * 2147483647)
        },
        // 分辨率
        getScreen: function () {
            this.data.ds = win.screen.width + "x" + win.screen.height
        },
        // 真彩色
        getColorDepth: function () {
            this.data.cl = win.screen ? win.screen.colorDepth + "-bit" : ""
        },
        // 是否禁用cookie
        getCookieEnabled: function () {
            this.data.ck = navigator.cookieEnabled ? "1" : "0"
        },
        // 是否禁用java
        getJavaEnabled: function () {
            this.data.ja = navigator.javaEnabled() ? "1" : "0"
        },
        // 语言
        getLang: function () {
            var a = navigator;
            this.data.ln = (a.M ? a.M : a.k ? a.k : a.language ? a.language : a.N ? a.N : "-").toLowerCase()
        },
        // url
        getUrl: function () {
            this.data.du = doc.URL;
        },
        // title
        getTittle: function () {
            this.data.dt = doc.title;
        },
        // 语言
        getLang: function () {
            var a = navigator;
            this.data.ln = (a.M ? a.M : a.k ? a.k : a.language ? a.language : a.N ? a.N : "-").toLowerCase()
        },
        //获取flash版本
        getFlash: function() {
            var f="-1",n=navigator;
            if (n.plugins && n.plugins.length) {
                for (var ii=0;ii<n.plugins.length;ii++) {
                    if (n.plugins[ii].name.indexOf('Shockwave Flash')!=-1) {
                        f=n.plugins[ii].description.split('Shockwave Flash ')[1];
                        break;
                    }
                }
            } else if (window.ActiveXObject) {
                for (var ii=10;ii>=2;ii--) {
                    try {
                        var fl=eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash."+ii+"');");
                        if (fl) { f=ii + '.0'; break; }
                    }
                    catch(e) {}
                }
            }
            if(f == "-1"){
                this.data.fl = f;
            }else{
                this.data.fl = f.substring(0,f.indexOf(".")+2);
            }
        },
        //统计帐号
        getAcId: function () {
            this.data.si = cfg.id
        },
        //来源
        getSource: function () {
            //var a = doc.referrer;
            var a = "http://www.google.com.hk/search?rlz=1C1AFAB_enCN449CN449&gcx=w&sourceid=chrome&ie=UTF-8&q=oauth-php";
            this.data.su = a ? a : ""
        },
        //搜索关键字模块
        getSe: function () {
            //var ref = doc.referrer;
            var a = "http://www.google.com.hk/search?rlz=1C1AFAB_enCN449CN449&gcx=w&sourceid=chrome&ie=UTF-8&q=oauth-php";
            if (ref) {
                //默认
                this.data.st = "1"
                var parse = ref.match(/^(([a-z]+):\/\/)?([^\/\?#]+)\/*([^\?#]*)\??([^#]*)#?(\w*)$/i);
                var refdomain =  parse[3];
                //站内
                if(refdomain.indexOf(cfg.dm) > -1){
                    this.data.st = "0";
                    return;
                }
                //搜索
                for (var i = 0, len = cfg.sengin.length; i < len; i++) {
                    console.log(cfg.sword[i]);
                    var e = mainU.queryUrl(ref,cfg.sword[i]);
                    console.log(e);
                    if (ref.indexOf(cfg.sengin[i]) > -1 && e) {
                        this.data.sw = e;
                        this.data.se = cfg.sindex[i];
                        this.data.st = "2";
                        return
                    }
                }
                return;
            }
        },
        //获取用户id
        getUid : function(){
            var uid = mainU.getCookie("sdna_uid");
            this.data.uid = uid;
        },
        //获取会话id
        getSid : function(){
            var sid = mainU.getCookie("sdna_sid");
            this.data.sid = sid;
        },
        //检查cookie
        ckCheck : function(){
            var uid = mainU.getCookie("sdna_uid"),
                sid = mainU.getCookie("sdna_sid");
            if(!uid.length){
                console.log('uid:'+uid.length);
                mainU.setCookie("sdna_uid",this.getRnd(),cfg.age,'/',this.getDomain());
            }
            if(!sid.length){
                console.log('sid:'+sid.length);
                mainU.setSession("sdna_sid",this.getRnd(),this.getDomain());
            }
        },
        //return domain
        getDomain : function(){
            var d=doc.domain;
            if (d.substring(0,4)=="www.") {
            d=d.substring(4,d.length);
            }
            return d;
        },
        getData : function(){
            this.ckCheck();
            this.getScreen();
            this.getColorDepth();
            this.getCookieEnabled();
            this.getJavaEnabled();
            this.getLang();
            this.getAcId();
            this.getSource();
            this.getSe();
            this.getUid();
            this.getSid();
            this.getFlash();
            this.getTittle();
            this.getUrl();
            console.log(this.getDomain());
        },
        buildUrl : function(){
            for (var arr = [], i = 0, len = param.length; i < len; i++) {
                var key= param[i],
                    val = this.data[key];
                val && arr.push(key + "=" + encodeURIComponent(val))
            }
            console.log(arr.join("&"));
            return arr.join("&");
        },
        log : function(){
            var img = new Image(1, 1);
            img.onload = function () {};
            img.src = this.protocol() + "123.125.114.142:8001/hm.gif?" + this.buildUrl();
        }
    });
    
    // main Utils
    var mainU = {
        /** 
         * 解析url或search字符串。
         * @method queryUrl
         * @static
         * @param {String} s url或search字符串
         * @param {String} key (Optional) 参数名。
         * @return {Json|String|Array|undefined} 如果key为空，则返回解析整个字符串得到的Json对象；否则返回参数值。有多个参数，或参数名带[]的，参数值为Array。
         */
        queryUrl: function(url, key) {
            url = url.replace(/^[^?=]*\?/ig, '').split('#')[0];
            var json = {};
            //考虑到key中可能有特殊符号如“[].”等，而[]却有是否被编码的可能，所以，牺牲效率以求严谨，就算传了key参数，也是全部解析url。
            url.replace(/(^|&)([^&=]+)=([^&]*)/g, function (a, b, key , value){
                key = decodeURIComponent(key);
                value = decodeURIComponent(value);
                if (!(key in json)) {
                    json[key] = /\[\]$/.test(key) ? [value] : value; //如果参数名以[]结尾，则当作数组
                }
                else if (json[key] instanceof Array) {
                    json[key].push(value);
                }
                else {
                    json[key] = [json[key], value];
                }
            });
            return key ? json[key] : json;
        },
        isDomain: function (hostname, domain) {
            if (typeof(domain) == 'string') {
                var hostname = hostname.replace(/:\d+/, ""),//去掉端口
                    domain = domain.replace(/:\d+/, ""),
                    is = hostname.indexOf(domain);
                return is >= 0 && is + domain.length == hostname.length ? !0 : !1
            } else {
                for (var len = domain.length, i = 0; i < len; i++) {
                    var domain2 = domain[i],
                        lenDomain = domain2.length,
                        is = hostname.indexOf(domain2);
                    if (is >= 0 && is + lenDomain == hostname.length) return domain2
                }
            }
            return domain
        },
        /**
         * 存储
         * @method set
         * @param {string} key
         * @param {string} value
         * @return void
         */
        setCookie:function(key, value,expires,path,domain,secure){
            console.log(domain);
            var path = path || "/",
                domain = domain || "",
                expires = expires || 3600000 * 24 * 365,
                secure = secure || "",
                now = new Date();
            if(typeof(expires)=="number"){
                now.setTime(now.getTime() + expires);
            }
            document.cookie =
                key + "=" + escape(value)
                + ";expires=" + now.toGMTString()
                + ";path="+ path
                + (domain == "" ? "" : ("; domain=" + domain))
                + (secure ? "; secure" : "");
        },
        
        setSession:function(key, value, domain){
            doc.cookie = key + "=" + escape(value) + "; domain=" + domain;
            console.log(domain);
        },
        /**
         * 读取
         * @method get
         * @param {string} key
         * @return string
         */
        getCookie:function(key){
            var a, reg = new RegExp("(^| )" + key + "=([^;]*)(;|$)");
            if(a = document.cookie.match(reg)){
                return unescape(a[2]);
            }else{
                return "";
            }
        },
        /*
         * 移除
         * @method remove
         * @param {string} key
         * @return void
         */
        removeCookie:function(key){
            var expires = - 3600000 * 24 * 365;
            this.set(key,"",expires);
        }
    };
    
    new main;
})(document, window);